package top.lingkang.mm.override;

import org.apache.ibatis.reflection.Reflector;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.util.MapUtil;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 配置 Reflector 反射解析，用于下划线转驼峰、驼峰转化 get 、set （推荐加载）
 *
 * @author lingkang
 * @create by 2024/3/1 17:30
 */
public class MagicReflectorFactory implements ReflectorFactory {
    private boolean classCacheEnabled = true;
    private final ConcurrentMap<Class<?>, MagicReflector> reflectorMap = new ConcurrentHashMap<>();

    public MagicReflectorFactory() {
    }

    @Override
    public boolean isClassCacheEnabled() {
        return classCacheEnabled;
    }

    @Override
    public void setClassCacheEnabled(boolean classCacheEnabled) {
        this.classCacheEnabled = classCacheEnabled;
    }

    @Override
    public Reflector findForClass(Class<?> type) {
        if (classCacheEnabled) {
            // synchronized (type) removed see issue #461
            return MapUtil.computeIfAbsent(reflectorMap, type, MagicReflector::new);
        }
        return new MagicReflector(type);
    }
}
